<?php
/**
 * Created by PhpStorm.
 * User: lelouchms
 * Date: 2019/3/26
 * Time: 16:43
 */

namespace app\common\library;


use app\common\exception\CustomerException;
use Redis;
use think\facade\Env;

class RedisUtil
{

    private $redis = null;

    private static $instance;

    public static function getInstance()
    {
        if (self::$instance == null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function __construct()
    {
        try {
            $this->redis = new \Redis();
            $this->redis->connect(Env::get("redis.hostname"), Env::get("redis.port"));
            $this->redis->select(1);
        } catch (\RedisException $e) {
            throw new CustomerException("redis启动错误: ");
        }
    }

    public function setList($key, $value)
    {
        if (empty($value)) return;
        $dataKey = $key . ":" . $value["orderNo"];
        $value['time'] = time();
        $value = json_encode($value);
        $this->redis->hset($key, $dataKey, $value);
    }

    public function get($key, $limit = null)
    {
        $getData = $this->redis->hGetAll($key);
        if (empty($getData)) return [];
        $returnData = [];
        foreach ($getData as $key => $value) {
            $returnData[$key] = json_decode($value, true);
        }
        if (empty($limit)) return $returnData;
        $filterData = [];
        $count = 0;
        foreach ($returnData as $key => $value) {
            if ($count < $limit) $filterData[$key] = $value;
        }
        return $returnData;
    }

    public function remove($key, $orderId)
    {
        $data_key = $key . ":" . $orderId;
        $keys = $this->redis->hKeys($key);
        if (in_array($data_key, $keys)) {
            $this->redis->hDel($key, $key . ":" . $orderId);
        }
    }

    /**
     * 得到redis实例
     * @return Redis|null
     */
    public function getRedis()
    {
        return $this->redis;
    }
}